local Piece = require "packages.chess-games.xiangqi.core.piece"

local Pawn = Piece:subclass("Xiangqi.Pawn")

function Pawn:initialize(id)
  Piece.initialize(self, id)

  self.name = 'pawn'
  self.redStr = '兵'
  self.blackStr = '卒'
end

---@param board integer[][]
---@param fromX integer
---@param fromY integer
---@param x integer
---@param y integer
function Pawn:canMoveTo(board, fromX, fromY, x, y)
  local dx = x - fromX
  local dy = y - fromY
  local myColor = self:getColor()

  -- 红兵：往上走
  if myColor == "red" then
    -- 过河前（y >= 6）：只能直走
    if fromY >= 6 then
      if dx ~= 0 or dy ~= -1 then
        return false
      end
    else
      -- 过河后（y <= 5）：可以直走或左右平走
      if not ((dx == 0 and dy == -1) or (math.abs(dx) == 1 and dy == 0)) then
        return false
      end
    end
  else
    -- 黑卒：往下走
    -- 过河前（y <= 5）：只能直走
    if fromY <= 5 then
      if dx ~= 0 or dy ~= 1 then
        return false
      end
    else
      -- 过河后（y >= 6）：可以直走或左右平走
      if not ((dx == 0 and dy == 1) or (math.abs(dx) == 1 and dy == 0)) then
        return false
      end
    end
  end

  -- 目标位置若有己方棋子，不可走
  local targetId = board[y][x]
  if targetId ~= 0 then
    local targetColor = (targetId > 0) and "red" or "black"
    if myColor == targetColor then
      return false
    end
  end

  return true
end

return Pawn

